/* eslint-disable react-hooks/exhaustive-deps */
import React, { FC, memo, useEffect, useRef, useState } from 'react'

import {
  fetchAddArticleCommentAction,
  fetchArticleListAction,
  fetchArticleCommentAction,
  fetchLiftRecordAction,
  fetchArticleLikeAction,
  fetchArticleViewAction
} from '@/store/module/share'
import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store'
import { ArticleDetailWrapper, LiftRecordWrapper, ShareWrapper } from './style'
import TopNavigate from './c-cnps/topNavigate'
import { formatTime, formatTimeAgo } from '@/utils/time'
import LtModel from '@/base-ui/lt-modal'
import LtAvatar from '@/base-ui/lt-avatar'
import LtButton from '@/base-ui/lt-button'

interface IState {
  children?: React.ReactNode
}

const Share: FC<IState> = memo(() => {
  const dispatch = useAppDispatch()

  // 获得对应的数据
  const [articleList, setArticleList] = useState<any>([])
  const [articlePage, setArticlePage] = useState<number>(1) // 文章的页码
  const [liftRecordPage, setLiftReaordPage] = useState<number>(1) // 随记的页码
  const [liftRecordList, setLiftRecordList] = useState<any>([]) // 随记列表
  const [liftRecordMoreText, setLiftRecordMoreText] = useState<string>('点击加载更多随记...')

  useEffect(() => {
    // 获得文章列表
    dispatch(fetchArticleListAction(articlePage)).then((res) => {
      if (res.payload.length === 0 || res.payload.length < 5) {
        setArticleList(res.payload)
        setMoreText('没有更多了')
      } else {
        setArticleList(res.payload)
        setMoreText('加载更多...')
      }
    })
    // 获得随记列表
    dispatch(fetchLiftRecordAction(liftRecordPage)).then((res: any) => {
      if (res.payload?.length < 5) {
        setLiftRecordMoreText('没有更多随记了')
      } else {
        setLiftRecordMoreText('点击加载更多随记...')
      }

      setLiftRecordList(res.payload)
    })
  }, [])

  // 获得头像信息
  const { avatar } = useAppSelector(
    (state) => ({
      avatar: state.options.avatar
    }),
    shallowEqualApp
  )

  // 渲染文章
  const [moreText, setMoreText] = useState<string>('加载更多...')
  const moreRef = useRef<HTMLDivElement | null>(null)
  const renderArticle = (isDesc = true) => {
    return articleList.map((item: any) => {
      return (
        <div key={item.id} className="article_item" onClick={() => openDetail(item)}>
          <div className="poster">
            <img src={item.poster} alt="poster" />
          </div>
          <div className="right">
            <h1 className="title">{item.title}</h1>
            {isDesc ? <div className="desc">{item.desc}</div> : ''}
            <div className="footer">
              <div className="time">{formatTime(item.created_at)}</div>
              <div className="options">
                <div className="item">
                  <span className="iconfont icon icon-dianzan"></span>
                  <span>{item.likes}</span>
                </div>
                <div className="item">
                  <span className="iconfont icon icon-yulan"></span>
                  <span>{item.views}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      )
    })
  }

  // 渲染文章详情的内容
  const renderDetailContent = () => {
    return (
      <>
        <h1>{currentArticle?.title}</h1>
        <div className="detail_top">
          <div className="time">{formatTime(currentArticle?.created_at)}</div>
          <div className="msg">
            <div className="msg_item">
              <span>{currentArticle?.likes}</span>
              <span className="iconfont icon icon-dianzan"></span>
            </div>
            <div className="msg_item">
              <span>{currentArticle?.views}</span>
              <span className="iconfont icon icon-yulan"></span>
            </div>
          </div>
        </div>
        <div className="desc">
          <span>{currentArticle?.desc}</span>
        </div>
        <div className="content">
          {currentArticle?.article_detail?.map((m: any, index: number) => {
            return (
              <div className="content_item" key={index}>
                <div className="text">{m.title}</div>
                {m.image.map((image: string, index: number) => {
                  return <img className="image" key={index} src={image} alt="图片" />
                })}
              </div>
            )
          })}
        </div>
      </>
    )
  }

  // 渲染点赞信息和预览信息
  const renderLikesAndViews = () => {
    return (
      <>
        <div className="likes_info">
          <div className="like_wrapper" onClick={likeHandle}>
            <span className="iconfont icon active icon-dianzan"></span>
          </div>
          <span className="likes_title">{likes}</span>
          <div className="likes_msg">
            <div className="likes_msg_item">
              <span>{currentArticle?.likes}</span>
              <span className="iconfont icon icon-dianzan"></span>
            </div>
            <div className="likes_msg_item">
              <span>{currentArticle?.views}</span>
              <span className="iconfont icon icon-yulan"></span>
            </div>
          </div>
        </div>
      </>
    )
  }
  // 给文章点赞
  const likeHandle = () => {
    dispatch(fetchArticleLikeAction(currentArticle.id)).then(() => {
      setLikes(likes + 1)
      articleList.forEach((item: any) => {
        if (item.id === currentArticle.id) {
          item.likes = likes + 1
        }
      })
    })
  }

  // 渲染输入评论部分
  const renderInputComment = () => {
    return (
      <>
        {' '}
        <div className="comment_header">
          <div className="header_left">
            <LtAvatar src={avatar} shape="square"></LtAvatar>
          </div>
          <div className="header_right">
            <textarea
              className="textarea"
              value={content}
              placeholder="对内容有什么看法?"
              onChange={(e) => setContent(e.target.value)}
            ></textarea>
            <div className="comment_input">
              <div className="name">
                <input
                  type="text"
                  className="name_input"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                />
              </div>
              <div className="btn">
                <LtButton
                  onClick={sendComment}
                  isLoading={isLoading}
                  disabled={disabled}
                ></LtButton>
              </div>
            </div>
          </div>
        </div>
      </>
    )
  }

  // 渲染评论部分
  const [moreCommentText, setMoreCommentText] = useState<string>('点击加载更多评论')
  const loadMoreComment = () => {
    if (moreCommentText === '点击加载更多评论') {
      setCommnetPage(commnetPage + 1)
      dispatch(
        fetchArticleCommentAction({
          article_id: currentArticle?.id,
          page: commnetPage + 1,
          size: 5
        })
      ).then((res: any) => {
        if (res.payload.length < 5) {
          setMoreCommentText('没有更多评论了')
        } else {
          setMoreCommentText('点击加载更多评论')
        }
        setCommentList([...commentList, ...res.payload])
      })
    }
  }
  const renderComment = () => {
    return commentList?.length === 0 ? (
      <div className="no_comment">暂无评论</div>
    ) : (
      <div>
        {commentList?.map((m: any) => {
          return (
            <div className="comment_item" key={m.id}>
              <LtAvatar src={m.avatar} shape="circle"></LtAvatar>
              <div className="comment_content">
                <div className="name_time">
                  <span className="c_name">{m.username}</span>
                  <span className="c_time">{formatTimeAgo(m.created_at)}</span>
                </div>
                <div className="comment_text">
                  <span className="c_t">{m.content}</span>
                </div>
              </div>
            </div>
          )
        })}
        <div className="more_comment" onClick={loadMoreComment}>
          {moreCommentText}
        </div>
      </div>
    )
  }

  // 渲染随记列表
  const renderLiftRecordList = () => {
    return (
      <LiftRecordWrapper>
        {liftRecordList?.map((m: any) => {
          return (
            <div className="lift_record_item" key={m.id}>
              <div className="left_time">
                <p className="time">{new Date(m.created_at).getFullYear()}</p>
                <p className="time">{new Date(m.created_at).getMonth() + 1}月</p>
                <p className="time day">{new Date(m.created_at).getDate()}</p>
  
              </div>
              <div className="right_content">
                <p className="title">{m.title}</p>
                {m.content.map((c: any, index: number) => {
                  return (
                    <p className="content" key={index}>
                      {c}
                    </p>
                  )
                })}
              </div>
              {m.image?.length > 0 && (
                <div className="image">
                  <img src={m.image} alt="" />
                </div>
              )}
            </div>
          )
        })}
        <div className="lift_record_more_text" onClick={loadMoreLiftRecord}>
          {liftRecordMoreText}
        </div>
      </LiftRecordWrapper>
    )
  }
  const loadMoreLiftRecord = () => {
    if (liftRecordMoreText === '点击加载更多随记...') {
      setLiftReaordPage(liftRecordPage + 1)
      dispatch(fetchLiftRecordAction(liftRecordPage + 1)).then((res: any) => {
        if (res.payload.length < 5) {
          setLiftRecordMoreText('没有更多随记了')
        } else {
          setLiftRecordMoreText('点击加载更多随记...')
        }
        setLiftRecordList([...liftRecordList, ...res.payload])
      })
    }
  }

  // 发送评论
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [disabled, setDisabled] = useState<boolean>(false)
  const [name, setName] = useState<string>('匿名') // 评论者的名字
  const [content, setContent] = useState<string>('') // 评论的内容
  const sendComment = () => {
    const data = {
      username: name,
      content,
      article_id: currentArticle?.id,
      avatar
    }
    setIsLoading(true)
    setDisabled(true)
    dispatch(fetchAddArticleCommentAction(data)).then((res: any) => {
      setIsLoading(false)
      setDisabled(false)
      setContent('')
      setCommentList([res.payload, ...commentList])
    })
  }

  // 文章详情的弹层
  const [commnetPage, setCommnetPage] = useState<number>(1) // 评论的页码
  const [commentList, setCommentList] = useState<any>() // 评论列表
  const [isModel, setIsModel] = useState<boolean>(false) // 是否显示弹层
  const [currentArticle, setCurrentArticle] = useState<any>([]) // 当前文章
  const [likes, setLikes] = useState<number>(0) // 点赞数
  const openDetail = (item: any) => {
    // 设置弹层
    setIsModel(false)
    setCurrentArticle(item)
    setLikes(item.likes)
    setIsModel(true)
    // 获得文章评论
    dispatch(fetchArticleCommentAction({ article_id: item?.id, page: commnetPage, size: 5 })).then(
      (res: any) => {
        if (res.payload.length < 5) {
          setMoreCommentText('没有更多评论了')
        } else {
          setMoreCommentText('点击加载更多评论')
        }
        setCommentList(res.payload)
      }
    )
    // 增加文章的浏览量
    dispatch(fetchArticleViewAction(item?.id))
  }
  const onClose = () => {
    setIsModel(false)
  }

  // 切换顶部的菜单
  const [type, setType] = useState<string>('文章')
  const chooseItem = (item: any) => {
    setType(item.name)
  }

  // 页面滚动加载更多文章
  const handleScroll = (e: React.UIEvent<HTMLElement>) => {
    if (isBottomOfPage(e) && moreText === '加载更多...') {
      setArticlePage(articlePage + 1)
      dispatch(fetchArticleListAction(articlePage + 1)).then((res) => {
        if (res.payload.length < 5) {
          setMoreText('没有更多了')
        } else {
          setMoreText('加载更多...')
        }
        setArticleList([...articleList, ...res.payload])
      })
    }
  }
  // 检查是否到达页面底部
  const isBottomOfPage = (event: React.UIEvent<HTMLElement>) => {
    const { scrollTop, offsetHeight, scrollHeight } = event.currentTarget
    return scrollTop + offsetHeight >= scrollHeight
  }

  return (
    <ShareWrapper onScroll={(e) => handleScroll(e)}>
      {/* 顶部导航 */}
      <TopNavigate chooseItem={chooseItem}></TopNavigate>
      {/* 文章部分或日志 */}
      {type === '文章' ? (
        <div>
          {renderArticle()}
          <div className="more" ref={moreRef}>
            {moreText}
          </div>
        </div>
      ) : (
        renderLiftRecordList()
      )}
      {/* 文章详情的弹层 */}
      <LtModel isModel={isModel} onClose={onClose}>
        <ArticleDetailWrapper>
          <div className="article_detail">
            {/* 渲染文章详情的内容 */}
            {renderDetailContent()}
            {/* 渲染点赞信息 */}
            {renderLikesAndViews()}
            <div className="comment_wrapper">
              <div className="left">
                {/* 输入评论部分 */}
                {renderInputComment()}
                {/* 评论部分 */}
                <div className="comment_list">{renderComment()}</div>
              </div>
              <div className="right_article">
                <div className="right">{renderArticle(false)}</div>
              </div>
            </div>
          </div>
        </ArticleDetailWrapper>
      </LtModel>
    </ShareWrapper>
  )
})

export default Share
